﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Windows.Forms;
using BL;
using DAL.Model;
using DevExpress.DataAccess.Sql;
using DevExpress.XtraReports.UI;

namespace UI.Reports
{
    public partial class FrmReportViewer : Form
    {
        private XtraReport _report;
        private readonly ReportController _reportController;
        private readonly string _reportPath;
        private readonly IEnumerable _datasource;
        private readonly IDictionary<string, object> _queryParameters;

        public FrmReportViewer(IEnumerable<GetCustomerLiability> datasource, string reportPath)
        {
            InitializeComponent();
            _datasource = datasource;
            _reportPath = reportPath;
            _reportController = new ReportController();
            LoadReport();
        }

        public FrmReportViewer(string reportPath, IDictionary<string, object> queryParameters)
        {
            InitializeComponent();
            _queryParameters = queryParameters;
            _reportPath = reportPath;
            _reportController = new ReportController();
            LoadReport();
        }

        /// <summary>
        /// Loads report viewer
        /// </summary>
        private void LoadReport()
        {
            try
            {
                _report = _reportController.GetReportFromPath(_reportPath);
                if (_report == null)
                {
                    return;
                }

                reportViewer.PrintingSystem = _report.PrintingSystem;
                var sqlDataSource = (SqlDataSource) _report.DataSource;
                sqlDataSource.Connection.ConnectionString =
                    ConfigurationManager.ConnectionStrings["WHS_Report"].ConnectionString;

                foreach (var parameter in sqlDataSource.Queries[0].Parameters)
                {
                    parameter.Value = _queryParameters[parameter.Name];
                }
                reportViewer.DocumentSource = _report;
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("Report file {0} does not exist", _reportPath), ex);
            }
        }
    }
}
